package com.dream.mqpushserver.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class MyProtocolDeCoder extends LengthFieldBasedFrameDecoder {

    /**
     * @param maxFrameLength    最大内容长度
     * @param lengthFieldOffset 内容长度字段偏移量
     * @param lengthFieldLength 内容字段本身长度
     */
    public MyProtocolDeCoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {

        System.out.println("decode request ");
        in = (ByteBuf) super.decode(ctx, in);
        if (in == null) {
            System.out.println("super decode is null ");
            return null;
        }
        // 1 + 4 + length
        if (in.readableBytes() < 5) {
            throw new RuntimeException("长度不足头部数据长度");
        }
        byte type = in.readByte();
        int length = in.readInt();
        if (in.readableBytes() != length) {
            throw new RuntimeException("剩余字符长度与预期长度不符");
        }
        byte[] bytes = new byte[length];
        in.readBytes(bytes);
        Request request = new Request();
        request.setType(type);
        request.setLength(length);
        request.setContent(new String(bytes));
        System.out.println("resolve request object ...  ");
        return request;
    }
}